package com.tusuo.stds.ui.main;

import android.content.Intent;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.tusuo.stds.MyApp;
import com.tusuo.stds.R;
import com.tusuo.stds.biz.CurrentUser;
import com.tusuo.stds.biz.PageStatus;
import com.tusuo.stds.di.DaggerScope;
import com.tusuo.stds.di.Injector;
import com.tusuo.stds.rest.ApiHelper;
import com.tusuo.stds.rest.QuestionBankList;
import com.tusuo.stds.ui.BaseToolbarFragment;
import com.tusuo.stds.ui.LabButton;
import com.tusuo.stds.ui.questionbank.QuestionBankTempActivity_;
import com.tusuo.stds.ui.similarity.SimilarityTempActivity_;
import com.tusuo.stds.util.Utils;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;
import org.androidannotations.api.BackgroundExecutor;
import org.parceler.Parcels;

import javax.inject.Inject;

import autodagger.AutoComponent;
import autodagger.AutoInjector;
import rx.Subscriber;
import timber.log.Timber;

/**
 * @author J.Huang
 * @version 1.0
 *
 */
@AutoComponent(
        dependencies = MyApp.class
)
@AutoInjector
@DaggerScope(QuestionBankFragment.class)
@EFragment(R.layout.frag_bank)
public class QuestionBankFragment extends BaseToolbarFragment {

    @Inject
    ApiHelper mApiHelper;
    @Inject
    CurrentUser mCurrentUser;

    @ViewById(R.id.bank_tv_without_data)
    TextView tvWithoutData;

    @ViewById(R.id.bank_tv_question_number)
    TextView tvQuestionNum;
    @ViewById(R.id.bank_tv_question_hint1)
    TextView tvQuestionHint1;
    @ViewById(R.id.bank_tv_question_hint2)
    TextView tvQuestionHint2;

    @ViewById(R.id.bank_btn_start)
    Button btnStart;
    @ViewById(R.id.bank_btn_similarity)
    LabButton btnSimilarity;

    @StringRes(R.string.toolbar_title_bank)
    String toolbarTitle;
    @StringRes(R.string.err_msg_server)
    String mErrMsgServer;
    @StringRes(R.string.bank_btn_challenge)
    String strBtnChallenge;
    @StringRes(R.string.bank_btn_close_wrong_question)
    String strBtnCloseWrongQuestion;

    private Subscriber<QuestionBankList> mGetBankListSubscriber = null;

    private QuestionBankList mQuestionBankList;

    @AfterInject
    void initDI() {
        Injector.initQuestionBankFragmentComponent().inject(this);
    }

    @AfterViews
    void init() {
        PageStatus pageStatus = new PageStatus(true, false, toolbarTitle);
        initData(pageStatus,null);

        showNoQuestionTips();
    }

    @Override
    public void onResume() {
        super.onResume();

        mGetBankListSubscriber = new GetBankListSubscriber();
        mApiHelper.getBankList(mGetBankListSubscriber);
    }

    @Override
    public void onPause() {
        if (mGetBankListSubscriber != null) {
            mGetBankListSubscriber.unsubscribe();
            mGetBankListSubscriber = null;
        }
        super.onPause();
    }

    @Override
    public void onDestroy() {
        BackgroundExecutor.cancelAll("refreshSimilarity", true);

        super.onDestroy();
    }

    @Override
    protected void findViews() {
        mToolbar = (Toolbar) getActivity().findViewById(R.id.bank_toolbar);
        mToolbarTitle = (TextView) getActivity().findViewById(R.id.bank_tv_toolbar_title);
    }

    private void showNoQuestionTips() {
        tvWithoutData.setVisibility(View.VISIBLE);

        tvQuestionNum.setVisibility(View.GONE);
        tvQuestionHint1.setVisibility(View.GONE);
        tvQuestionHint2.setVisibility(View.GONE);
        btnSimilarity.setVisibility(View.GONE);

        btnStart.setText(strBtnChallenge);
        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getActivity() instanceof MainActivity_) {
                    ((MainActivity_)getActivity()).toChallengeTab();
                }
            }
        });
    }

    private void showQuestionTips() {
        tvWithoutData.setVisibility(View.GONE);

        tvQuestionNum.setVisibility(View.VISIBLE);
        tvQuestionHint1.setVisibility(View.VISIBLE);
        tvQuestionHint2.setVisibility(View.VISIBLE);

        btnStart.setText(strBtnCloseWrongQuestion);
        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getContext(), QuestionBankTempActivity_.class);
                intent.putExtra(QuestionBankList.EXTRA_NAME, Parcels.wrap(mQuestionBankList));
                getContext().startActivity(intent);
            }
        });
    }

    @Click(R.id.bank_btn_similarity)
    void clickSimilarityBtn() {
        if (Utils.UI.isFastDoubleClick()) {
            return;
        }

        Intent intent = new Intent();
        intent.setClass(getContext(), SimilarityTempActivity_.class);
        getContext().startActivity(intent);
    }

    private boolean mIsSimilarityOpening = false;

    @UiThread
    void checkSimilarity() {
        if (btnStart != null
                && btnSimilarity != null
                && mCurrentUser != null) {
            if (btnStart.getVisibility() == View.VISIBLE && mCurrentUser.getOpenSimilarityState()) {
                btnSimilarity.setVisibility(View.VISIBLE);
                mIsSimilarityOpening = true;
            } else {
                btnSimilarity.setVisibility(View.GONE);
                mIsSimilarityOpening = false;
            }
        }
    }

    @Background(id = "refreshSimilarity", delay = 500)
    void refreshSimilarity() {
        try {
            for (int i = 0; i < 20; i++) {
                checkSimilarity();
                if (mIsSimilarityOpening) {
                    break;
                }
                Thread.sleep(500);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private class GetBankListSubscriber extends Subscriber<QuestionBankList> {
        @Override
        public void onCompleted() {
            refreshSimilarity();
        }

        @Override
        public void onError(Throwable e) {
            Utils.UI.showToastShort(mErrMsgServer);
            showNoQuestionTips();
        }

        @Override
        public void onNext(final QuestionBankList questionBankList) {
            if (questionBankList.checkState(getContext())) {
                mQuestionBankList = questionBankList;
                tvQuestionNum.setText(String.valueOf(mQuestionBankList.Total));

                if (mQuestionBankList.Total != 0) {
                    showQuestionTips();
                }else {
                    showNoQuestionTips();
                }
            }
        }
    }
}
